// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core;
using Admin.NET.Core.Model;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.SignalR;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// WMS 大屏数据服务
/// </summary>
public class WmsDashboardService : ITransient
{
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly IHubContext<WmsDashboardHub, IWmsDashboardHub> _hubContext;

    public WmsDashboardService(
        ISqlSugarClient sqlSugarClient,
        IHubContext<WmsDashboardHub, IWmsDashboardHub> hubContext)
    {
        _sqlSugarClient = sqlSugarClient;
        _hubContext = hubContext;
    }

    /// <summary>
    /// 获取库存数量占比数据
    /// </summary>
    public async Task<List<InventoryRatioData>> GetInventoryQuantityRatioAsync(long? tenantId = null)
    {
        var warehouseModel = _sqlSugarClient.Queryable<WarePlaceModel>().Filter("", true);

        var warePlaces = await warehouseModel.ToListAsync();
        
        var data = new List<InventoryRatioData>();
        var totalQuantity = 0m;

        foreach (var warePlace in warePlaces)
        {
            if (string.IsNullOrWhiteSpace(warePlace.ShopName))
                continue;

            try
            {
                var goodsList = System.Text.Json.JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName) ?? new List<WarePlaceGoods>();
                var placeTotalQuantity = goodsList.Sum(g => g.Quantity);
                
                if (placeTotalQuantity > 0)
                {
                    totalQuantity += placeTotalQuantity;
                    data.Add(new InventoryRatioData
                    {
                        Name = warePlace.WarePlaceName,
                        Value = placeTotalQuantity
                    });
                }
            }
            catch { }
        }

        // 计算占比
        foreach (var item in data)
        {
            item.Percentage = totalQuantity > 0 ? (item.Value / totalQuantity * 100) : 0;
        }

        return data.OrderByDescending(x => x.Value).Take(10).ToList();
    }

    /// <summary>
    /// 获取库存金额占比数据
    /// </summary>
    public async Task<List<InventoryRatioData>> GetInventoryAmountRatioAsync(long? tenantId = null)
    {
        var warehouseModel = _sqlSugarClient.Queryable<WarePlaceModel>().Filter("", true);

        var warePlaces = await warehouseModel.ToListAsync();
        
        var data = new List<InventoryRatioData>();
        var totalAmount = 0m;

        foreach (var warePlace in warePlaces)
        {
            if (string.IsNullOrWhiteSpace(warePlace.ShopName))
                continue;

            try
            {
                var goodsList = System.Text.Json.JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName) ?? new List<WarePlaceGoods>();
                var placeTotalAmount = goodsList.Sum(g => g.Amount);
                
                if (placeTotalAmount > 0)
                {
                    totalAmount += placeTotalAmount;
                    data.Add(new InventoryRatioData
                    {
                        Name = warePlace.WarePlaceName,
                        Value = placeTotalAmount
                    });
                }
            }
            catch { }
        }

        // 计算占比
        foreach (var item in data)
        {
            item.Percentage = totalAmount > 0 ? (item.Value / totalAmount * 100) : 0;
        }

        return data.OrderByDescending(x => x.Value).Take(10).ToList();
    }

    /// <summary>
    /// 获取入库统计数据
    /// </summary>
    public async Task<InboundStatisticsData> GetInboundStatisticsAsync(long? tenantId = null)
    {
        var today = DateTime.Now.Date;
        var monthStart = new DateTime(today.Year, today.Month, 1);

        // 今日入库统计（排除已删除的数据）
        var todayInbound = await _sqlSugarClient.Queryable<Sysinstockorder>()
            .Filter("", true)
            .Where(x => x.InDate >= today && x.InDate < today.AddDays(1) && x.IsDelete == false)
            .Select(x => new { x.InQuantity, x.WarehouseAmount })
            .ToListAsync();

        // 本月入库统计（排除已删除的数据）
        var monthInbound = await _sqlSugarClient.Queryable<Sysinstockorder>()
            .Filter("", true)
            .Where(x => x.InDate >= monthStart && x.InDate < today.AddDays(1) && x.IsDelete == false)
            .Select(x => new { x.InQuantity, x.WarehouseAmount })
            .ToListAsync();

        // 最近30天的趋势数据（优化：一次查询获取所有数据，排除已删除的数据）
        var startDate = today.AddDays(-29).Date;
        var trendData = await _sqlSugarClient.Queryable<Sysinstockorder>()
            .Filter("", true)
            .Where(x => x.InDate >= startDate && x.InDate < today.AddDays(1) && x.IsDelete == false)
            .Select(x => new { 
                Date = x.InDate.Date, 
                InQuantity = x.InQuantity, 
                WarehouseAmount = x.WarehouseAmount 
            })
            .ToListAsync();

        // 按日期分组统计
        var trendsDict = trendData
            .GroupBy(x => x.Date)
            .ToDictionary(g => g.Key, g => new { 
                Quantity = g.Sum(x => x.InQuantity), 
                Amount = g.Sum(x => x.WarehouseAmount) 
            });

        // 构建30天趋势（包括没有数据的日期）
        var trends = new List<StatisticalTrend>();
        for (int i = 29; i >= 0; i--)
        {
            var date = today.AddDays(-i);
            var data = trendsDict.ContainsKey(date) 
                ? trendsDict[date] 
                : new { Quantity = 0, Amount = 0m };

            trends.Add(new StatisticalTrend
            {
                Date = date.ToString("MM/dd"),
                Quantity = data.Quantity,
                Amount = data.Amount
            });
        }

        return new InboundStatisticsData
        {
            TodayInboundQuantity = todayInbound.Sum(x => x.InQuantity),
            TodayInboundAmount = todayInbound.Sum(x => x.WarehouseAmount),
            MonthInboundQuantity = monthInbound.Sum(x => x.InQuantity),
            MonthInboundAmount = monthInbound.Sum(x => x.WarehouseAmount),
            Trends = trends
        };
    }

    /// <summary>
    /// 获取出库统计数据
    /// </summary>
    public async Task<OutboundStatisticsData> GetOutboundStatisticsAsync(long? tenantId = null)
    {
        var today = DateTime.Now.Date;
        var monthStart = new DateTime(today.Year, today.Month, 1);

        // 今日出库统计（排除已删除的数据）
        var todayOutbound = await _sqlSugarClient.Queryable<Sysoutstockorder>()
            .Filter("", true)
            .Where(x => x.OutDate >= today && x.OutDate < today.AddDays(1) && x.IsDelete == false)
            .Select(x => new { x.OutQuantity, x.OutbouAmount })
            .ToListAsync();

        // 本月出库统计（排除已删除的数据）
        var monthOutbound = await _sqlSugarClient.Queryable<Sysoutstockorder>()
            .Filter("", true)
            .Where(x => x.OutDate >= monthStart && x.OutDate < today.AddDays(1) && x.IsDelete == false)
            .Select(x => new { x.OutQuantity, x.OutbouAmount })
            .ToListAsync();

        // 最近30天的趋势数据（优化：一次查询获取所有数据，排除已删除的数据）
        var startDate = today.AddDays(-29).Date;
        var trendData = await _sqlSugarClient.Queryable<Sysoutstockorder>()
            .Filter("", true)
            .Where(x => x.OutDate >= startDate && x.OutDate < today.AddDays(1) && x.IsDelete == false)
            .Select(x => new { 
                Date = x.OutDate.Date, 
                OutQuantity = x.OutQuantity, 
                OutbouAmount = x.OutbouAmount 
            })
            .ToListAsync();

        // 按日期分组统计
        var trendsDict = trendData
            .GroupBy(x => x.Date)
            .ToDictionary(g => g.Key, g => new { 
                Quantity = g.Sum(x => x.OutQuantity), 
                Amount = g.Sum(x => x.OutbouAmount) 
            });

        // 构建30天趋势（包括没有数据的日期）
        var trends = new List<StatisticalTrend>();
        for (int i = 29; i >= 0; i--)
        {
            var date = today.AddDays(-i);
            var data = trendsDict.ContainsKey(date) 
                ? trendsDict[date] 
                : new { Quantity = 0, Amount = 0m };

            trends.Add(new StatisticalTrend
            {
                Date = date.ToString("MM/dd"),
                Quantity = data.Quantity,
                Amount = data.Amount
            });
        }

        return new OutboundStatisticsData
        {
            TodayOutboundQuantity = (todayOutbound?.Sum(x => x.OutQuantity)) ?? 0,
            TodayOutboundAmount = (todayOutbound?.Sum(x => x.OutbouAmount)) ?? 0,
            MonthOutboundQuantity = (monthOutbound?.Sum(x => x.OutQuantity)) ?? 0,
            MonthOutboundAmount = (monthOutbound?.Sum(x => x.OutbouAmount)) ?? 0,
            Trends = trends
        };
    }

    /// <summary>
    /// 获取代办事项
    /// </summary>
    public async Task<List<TodoTaskData>> GetTodoTasksAsync(long? tenantId = null)
    {
        var tasks = new List<TodoTaskData>();

        // 待审核的入库单（排除已删除的数据）
        var inboundQuery = _sqlSugarClient.Queryable<Sysinstockorder>()
            .Filter("", true)
            .Where(x => x.DocumentStatus == DocumentStatusEnum.Draft && x.IsDelete == false);

        var inboundOrders = await inboundQuery
            .OrderByDescending(x => x.InDate)
            .Take(5)
            .Select(x => new { x.Id, x.Code, x.InDate, x.Remark })
            .ToListAsync();

        foreach (var order in inboundOrders)
        {
            tasks.Add(new TodoTaskData
            {
                Id = order.Id,
                TaskType = "入库审核",
                Title = $"入库单 {order.Code} 待审核",
                Description = order.Remark ?? "入库单待审核",
                Priority = 2,
                CreateTime = order.InDate
            });
        }

        // 待审核的出库单（排除已删除的数据）
        var outboundQuery = _sqlSugarClient.Queryable<Sysoutstockorder>()
            .Filter("", true)
            .Where(x => x.DocumentStatus == DocumentStatusEnum.Draft && x.IsDelete == false);

        var outboundOrders = await outboundQuery
            .OrderByDescending(x => x.OutDate)
            .Take(5)
            .Select(x => new { x.Id, x.Code, x.OutDate, x.Remark })
            .ToListAsync();

        foreach (var order in outboundOrders)
        {
            tasks.Add(new TodoTaskData
            {
                Id = order.Id,
                TaskType = "出库审核",
                Title = $"出库单 {order.Code} 待审核",
                Description = order.Remark ?? "出库单待审核",
                Priority = 2,
                CreateTime = order.OutDate
            });
        }

        return tasks.OrderByDescending(x => x.CreateTime).Take(10).ToList();
    }

    /// <summary>
    /// 获取预警信息
    /// </summary>
    public async Task<List<AlertData>> GetAlertsAsync(long? tenantId = null)
    {
        var alerts = new List<AlertData>();

        // 检查库存不足
        var warehouseModel = _sqlSugarClient.Queryable<WarePlaceModel>().Filter("", true);

        var warePlaces = await warehouseModel.ToListAsync();
        
        foreach (var warePlace in warePlaces)
        {
            if (string.IsNullOrWhiteSpace(warePlace.ShopName))
                continue;

            try
            {
                var goodsList = System.Text.Json.JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName) ?? new List<WarePlaceGoods>();
                
                foreach (var goods in goodsList)
                {
                    if (goods.Quantity <= 0)
                    {
                        alerts.Add(new AlertData
                        {
                            Id = goods.GoodsId,
                            AlertType = "库存不足",
                            Title = $"{goods.GoodsName} 库存已用完",
                            Content = $"库位 {warePlace.WarePlaceName} 的 {goods.GoodsName} 库存数量为 0",
                            UrgencyLevel = 3,
                            CreateTime = DateTime.Now
                        });
                    }
                }
            }
            catch { }
        }

        return alerts.OrderByDescending(x => x.UrgencyLevel).ThenByDescending(x => x.CreateTime).Take(20).ToList();
    }

    /// <summary>
    /// 获取入库排名
    /// </summary>
    public async Task<List<RankingData>> GetInboundRankingAsync(long? tenantId = null)
    {
        var monthStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        
        // 获取本月所有的入库记录（排除已删除的数据）
        var inboundRecords = await _sqlSugarClient.Queryable<Sysinstockorder>()
            .Filter("", true)
            .Where(x => x.InDate >= monthStart && x.InDate < DateTime.Now.Date.AddDays(1) && x.IsDelete == false)
            .Select(x => new { x.GoodsName, x.InQuantity, x.WarehouseAmount })
            .ToListAsync();

        // 处理商品名称并分组统计
        var goodsData = new List<(string Name, int Quantity, decimal Amount)>();
        
        foreach (var record in inboundRecords)
        {
            if (string.IsNullOrWhiteSpace(record.GoodsName))
                continue;

            // 如果商品名称包含多个商品（用逗号、分号等分隔），则需要拆分
            var goodsNames = record.GoodsName.Split(new[] { ',', '，', ';', '；', '、' }, StringSplitOptions.RemoveEmptyEntries);
            
            foreach (var goodsName in goodsNames)
            {
                var name = goodsName.Trim();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    // 将数量和金额按商品数量平均分配（如果需要更精确的分摊，可以进一步完善）
                    goodsData.Add((name, record.InQuantity, record.WarehouseAmount));
                }
            }
        }

        // 按商品名称分组统计
        var groupedData = goodsData
            .GroupBy(x => x.Name)
            .Select(g => new
            {
                Name = g.Key,
                Quantity = g.Sum(x => x.Quantity),
                Amount = g.Sum(x => x.Amount)
            })
            .OrderByDescending(x => x.Amount)
            .Take(10)
            .ToList();

        var result = new List<RankingData>();
        int rank = 1;
        foreach (var item in groupedData)
        {
            result.Add(new RankingData
            {
                Rank = rank++,
                Name = item.Name,
                Quantity = item.Quantity,
                Amount = item.Amount
            });
        }

        return result;
    }

    /// <summary>
    /// 获取出库排名
    /// </summary>
    public async Task<List<RankingData>> GetOutboundRankingAsync(long? tenantId = null)
    {
        var monthStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        
        // 获取本月所有的出库记录（排除已删除的数据）
        var outboundRecords = await _sqlSugarClient.Queryable<Sysoutstockorder>()
            .Filter("", true)
            .Where(x => x.OutDate >= monthStart && x.OutDate < DateTime.Now.Date.AddDays(1) && x.IsDelete == false)
            .Select(x => new { x.GoodsName, x.OutQuantity, x.OutbouAmount })
            .ToListAsync();

        // 处理商品名称并分组统计
        var goodsData = new List<(string Name, int Quantity, decimal Amount)>();
        
        foreach (var record in outboundRecords)
        {
            if (string.IsNullOrWhiteSpace(record.GoodsName))
                continue;

            // 如果商品名称包含多个商品（用逗号、分号等分隔），则需要拆分
            var goodsNames = record.GoodsName.Split(new[] { ',', '，', ';', '；', '、' }, StringSplitOptions.RemoveEmptyEntries);
            
            foreach (var goodsName in goodsNames)
            {
                var name = goodsName.Trim();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    // 将数量和金额按商品数量平均分配（如果需要更精确的分摊，可以进一步完善）
                    goodsData.Add((name, record.OutQuantity, record.OutbouAmount));
                }
            }
        }

        // 按商品名称分组统计
        var groupedData = goodsData
            .GroupBy(x => x.Name)
            .Select(g => new
            {
                Name = g.Key,
                Quantity = g.Sum(x => x.Quantity),
                Amount = g.Sum(x => x.Amount)
            })
            .OrderByDescending(x => x.Amount)
            .Take(10)
            .ToList();

        var result = new List<RankingData>();
        int rank = 1;
        foreach (var item in groupedData)
        {
            result.Add(new RankingData
            {
                Rank = rank++,
                Name = item.Name,
                Quantity = item.Quantity,
                Amount = item.Amount
            });
        }

        return result;
    }

    /// <summary>
    /// 获取系统消息（从实际的入库单和出库单数据生成）
    /// </summary>
    public async Task<SystemMessageData> GetSystemMessagesAsync(long? tenantId = null)
    {
        var messages = new List<MessageItem>();

        try
        {
            // 获取最近24小时的入库单数量（排除已删除的数据）
            var todayInboundCount = await _sqlSugarClient.Queryable<Sysinstockorder>()
                .Filter("", true)
                .Where(x => x.InDate >= DateTime.Now.Date && x.InDate < DateTime.Now && x.IsDelete == false)
                .CountAsync();

            if (todayInboundCount > 0)
            {
                messages.Add(new MessageItem
                {
                    Content = $"今日完成 {todayInboundCount} 笔入库单",
                    Time = DateTime.Now.AddMinutes(-1),
                    Type = "success"
                });
            }

            // 获取最近24小时的出库单数量（排除已删除的数据）
            var todayOutboundCount = await _sqlSugarClient.Queryable<Sysoutstockorder>()
                .Filter("", true)
                .Where(x => x.OutDate >= DateTime.Now.Date && x.OutDate < DateTime.Now && x.IsDelete == false)
                .CountAsync();

            if (todayOutboundCount > 0)
            {
                messages.Add(new MessageItem
                {
                    Content = $"今日完成 {todayOutboundCount} 笔出库单",
                    Time = DateTime.Now.AddMinutes(-2),
                    Type = "success"
                });
            }

            // 获取待审核的入库单数量（排除已删除的数据）
            var pendingInboundCount = await _sqlSugarClient.Queryable<Sysinstockorder>()
                .Filter("", true)
                .Where(x => x.DocumentStatus == DocumentStatusEnum.Draft && x.IsDelete == false)
                .CountAsync();

            if (pendingInboundCount > 0)
            {
                messages.Add(new MessageItem
                {
                    Content = $"有待审核的入库单 {pendingInboundCount} 笔",
                    Time = DateTime.Now.AddMinutes(-3),
                    Type = "warning"
                });
            }

            // 获取待审核的出库单数量（排除已删除的数据）
            var pendingOutboundCount = await _sqlSugarClient.Queryable<Sysoutstockorder>()
                .Filter("", true)
                .Where(x => x.DocumentStatus == DocumentStatusEnum.Draft && x.IsDelete == false)
                .CountAsync();

            if (pendingOutboundCount > 0)
            {
                messages.Add(new MessageItem
                {
                    Content = $"有待审核的出库单 {pendingOutboundCount} 笔",
                    Time = DateTime.Now.AddMinutes(-4),
                    Type = "warning"
                });
            }

            // 获取最近的入库单（排除已删除的数据）
            var recentInbound = await _sqlSugarClient.Queryable<Sysinstockorder>()
                .Filter("", true)
                .Where(x => x.IsDelete == false)
                .OrderByDescending(x => x.InDate)
                .Take(1)
                .Select(x => new { x.Code, x.InDate })
                .FirstAsync();

            if (recentInbound != null)
            {
                messages.Add(new MessageItem
                {
                    Content = $"最新入库: {recentInbound.Code}",
                    Time = recentInbound.InDate,
                    Type = "info"
                });
            }

            // 获取最近的出库单（排除已删除的数据）
            var recentOutbound = await _sqlSugarClient.Queryable<Sysoutstockorder>()
                .Filter("", true)
                .Where(x => x.IsDelete == false)
                .OrderByDescending(x => x.OutDate)
                .Take(1)
                .Select(x => new { x.Code, x.OutDate })
                .FirstAsync();

            if (recentOutbound != null)
            {
                messages.Add(new MessageItem
                {
                    Content = $"最新出库: {recentOutbound.Code}",
                    Time = recentOutbound.OutDate,
                    Type = "info"
                });
            }

            // 添加系统状态消息
            messages.Add(new MessageItem
            {
                Content = $"系统运行正常 - {DateTime.Now:HH:mm:ss}",
                Time = DateTime.Now,
                Type = "info"
            });
        }
        catch (Exception ex)
        {
            messages.Add(new MessageItem
            {
                Content = $"获取系统消息异常: {ex.Message}",
                Time = DateTime.Now,
                Type = "error"
            });
        }

        // 按时间倒序排列，最多返回10条
        return new SystemMessageData
        {
            Messages = messages.OrderByDescending(x => x.Time).Take(10).ToList()
        };
    }

    /// <summary>
    /// 推送所有大屏数据（优化：批次并行执行，避免连接池压力）
    /// </summary>
    public async Task BroadcastDashboardDataAsync(long? tenantId = null)
    {
        // 强制推送到所有可能的组，确保所有客户端都能收到数据
        var groupsToPush = new List<string> 
        { 
            "GROUP_DASHBOARD_0",  // 默认组
            "GROUP_DASHBOARD_1300000000001"  // 租户组
        };
        
        Console.WriteLine($"准备推送到 {groupsToPush.Count} 个组: {string.Join(", ", groupsToPush)}");
        
        // 向所有相关组推送数据
        foreach (var groupName in groupsToPush)
        {
            Console.WriteLine($"开始推送数据到组: {groupName}");
            await BroadcastToGroup(groupName, tenantId);
        }
        
        Console.WriteLine($"所有组的数据推送完成");
    }
    
    /// <summary>
    /// 向指定组推送数据（优化：并行查询提升速度）
    /// </summary>
    private async Task BroadcastToGroup(string groupName, long? tenantId)
    {
        
        try
        {
            Console.WriteLine($"开始推送大屏数据到组: {groupName}");
            
            // 并行执行所有查询，大幅提升速度
            var queryStartTime = DateTime.Now;
            
            // 启动所有查询任务（并行执行）
            var inventoryQuantityTask = GetInventoryQuantityRatioAsync(tenantId);
            var inventoryAmountTask = GetInventoryAmountRatioAsync(tenantId);
            var inboundStatsTask = GetInboundStatisticsAsync(tenantId);
            var outboundStatsTask = GetOutboundStatisticsAsync(tenantId);
            var todoTasksTask = GetTodoTasksAsync(tenantId);
            var alertsTask = GetAlertsAsync(tenantId);
            var inboundRankingTask = GetInboundRankingAsync(tenantId);
            var outboundRankingTask = GetOutboundRankingAsync(tenantId);
            var systemMessagesTask = GetSystemMessagesAsync(tenantId);
            
            // 等待所有查询完成
            await Task.WhenAll(
                inventoryQuantityTask,
                inventoryAmountTask,
                inboundStatsTask,
                outboundStatsTask,
                todoTasksTask,
                alertsTask,
                inboundRankingTask,
                outboundRankingTask,
                systemMessagesTask
            );
            
            var queryEndTime = DateTime.Now;
            var queryDuration = (queryEndTime - queryStartTime).TotalMilliseconds;
            Console.WriteLine($"所有查询完成，耗时: {queryDuration:F2}ms");
            
            // 获取查询结果
            var inventoryQuantity = await inventoryQuantityTask;
            Console.WriteLine($"库存数量占比数据: {inventoryQuantity.Count} 条");
            
            var inventoryAmount = await inventoryAmountTask;
            Console.WriteLine($"库存金额占比数据: {inventoryAmount.Count} 条");
            
            var inboundStats = await inboundStatsTask;
            Console.WriteLine($"入库统计数据已获取");
            
            var outboundStats = await outboundStatsTask;
            Console.WriteLine($"出库统计数据已获取");
            
            var todoTasks = await todoTasksTask;
            Console.WriteLine($"代办事项数据: {todoTasks.Count} 条");
            
            var alerts = await alertsTask;
            Console.WriteLine($"预警信息数据: {alerts.Count} 条");
            
            var inboundRanking = await inboundRankingTask;
            Console.WriteLine($"入库排名数据: {inboundRanking.Count} 条");
            
            var outboundRanking = await outboundRankingTask;
            Console.WriteLine($"出库排名数据: {outboundRanking.Count} 条");
            
            var systemMessages = await systemMessagesTask;
            Console.WriteLine($"系统消息数据: {systemMessages.Messages.Count} 条");

            // 推送数据到客户端
            Console.WriteLine($"准备推送数据到组 {groupName} 的客户端");
            var groupClient = _hubContext.Clients.Groups(groupName);
            
            // 推送各个数据项
            var pushTasks = new List<Task>
            {
                groupClient.ReceiveInventoryQuantityRatio(inventoryQuantity),
                groupClient.ReceiveInventoryAmountRatio(inventoryAmount),
                groupClient.ReceiveInboundStatistics(inboundStats),
                groupClient.ReceiveOutboundStatistics(outboundStats),
                groupClient.ReceiveTodoTasks(todoTasks),
                groupClient.ReceiveAlerts(alerts),
                groupClient.ReceiveInboundRanking(inboundRanking),
                groupClient.ReceiveOutboundRanking(outboundRanking),
                groupClient.ReceiveSystemMessages(systemMessages)
            };
            
            await Task.WhenAll(pushTasks);
            Console.WriteLine($"数据推送到组 {groupName} 完成，共推送了 {pushTasks.Count} 条消息");
        }
        catch (Exception ex)
        {
            // 记录错误但不抛出，避免影响定时任务
            Console.WriteLine($"WMS Dashboard 数据推送到组 {groupName} 失败: {ex.Message}");
            System.Diagnostics.Debug.WriteLine($"WMS Dashboard Error: {ex}");
        }
    }
}


